package net.xxcl.exam.controller;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.xxcl.exam.pojo.Criteria;
import net.xxcl.exam.pojo.Score;
import net.xxcl.exam.pojo.Student;
import net.xxcl.exam.service.StudentService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * student: 夏汛
 * Date: 11-12-22
 * Time: 上午11:46
 */
@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/getStudentState",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> getStudentState(HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Student student = (Student)request.getSession().getAttribute("student");
        responseMap.put("state",student.getState());
        return responseMap;
    }

    /**
     * 获取考生列表
     * @param start
     * @param limit
     * @param cardid
     * @param number
     * @param username
     * @param classids
     * @return
     */
    @RequestMapping(value = "/students",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> getKemus(@RequestParam("start") Integer start,
                                                     @RequestParam("limit") Integer limit,
                                                     @RequestParam(value = "cardid",required = false) String cardid,
                                                     @RequestParam(value = "number",required = false) String number,
                                                     @RequestParam(value = "username",required = false) String username,
                                                     @RequestParam(value = "classids",required = false) String classids){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        //加上查询条件
        if(!(cardid==null || cardid.equals(""))) criteria.put("blurredCardid","%"+cardid+"%");
        if(!(number==null || number.equals(""))) criteria.put("blurredNumber","%"+number+"%");
        if(!(username==null || username.equals(""))) criteria.put("blurredUsername","%"+username+"%");
        if(!(classids==null || classids.equals(""))){
            String[] str = classids.split(",");
            List<String> classList = new ArrayList<String>();
            for(String s:str){
                classList.add(s);
            }
            criteria.put("classids",classList);
        }
        int total = studentService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<Student> list = studentService.selectByExample(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 新增或保存
     * @param student
     * @return
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> saveOrUpdate(@ModelAttribute("student") Student student){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try{
            Criteria criteria = new Criteria();
            criteria.put("cardid",student.getCardid());
            List<Student> students = studentService.selectByExample(criteria);
            //如果查询出没有该身份证号码，或者修改时没有修改身份证号码，允许
            if(students.size()==0 || students.get(0).getId().equals(student.getId())){
                //新增考生
                if(student.getId()==null){System.out.println();
                    //截取身份证号码后6位作为密码
                    String cardid = student.getCardid();
                    student.setPassword(cardid.substring((cardid.length()-6),cardid.length()));
                    studentService.insert(student);
                    responseMap.put("method", "Create");
                    responseMap.put("success", "true");
                    responseMap.put("info", "新增成功，初始密码为"+student.getPassword()+"!");
                }
                //编辑考生
                else {
                    student.setState(1);
                    studentService.updateByPrimaryKeySelective(student);
                    responseMap.put("success", "true");
                    responseMap.put("info", "编辑成功！");
                }
            } else {
                responseMap.put("info", "身份证号码已经存在");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
        }
        return responseMap;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @RequestMapping(value="/remove",method=RequestMethod.POST)
    public @ResponseBody Map<String,Object> remove(@RequestParam("ids") String ids){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try {
            studentService.deletestudent(ids);
            responseMap.put("success", "true");
            responseMap.put("info", "删除成功！");
            return responseMap;
        }catch(Exception e) {
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
            return responseMap;
        }
    }

    /**
     * 重置密码
     * @param ids
     * @return
     */
    @RequestMapping(value="/resetPass",method=RequestMethod.POST)
    public @ResponseBody Map<String,Object> resetPass(@RequestParam("ids") String ids){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try {
            studentService.resetPass(ids);
            responseMap.put("success", "true");
            responseMap.put("info", "选中用户密码重置为身份证号后6位！");
            return responseMap;
        }catch(Exception e) {
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
            return responseMap;
        }
    }

    /**
     * 关联试卷
     * @param ids
     * @return
     */
    @RequestMapping(value="/glPaper",method=RequestMethod.POST)
    public @ResponseBody Map<String,Object> glPaper(@RequestParam("ids") String ids,@RequestParam("paperid") Integer paperid){
        Map<String,Object> responseMap = new HashMap<String,Object>();
        try {
            String[] str = ids.split(",");
            int totalError = 0;
            int totalExist = 0;
            int totalSuccess = 0;
            for(String id:str){
                int i = studentService.glPaper(Integer.parseInt(id),paperid);
                if(i==1){
                    totalSuccess++;
                } else if (i==2){
                    totalExist++;
                } else {
                    totalError++;
                }
            }
            responseMap.put("info", "关联成功"+totalSuccess+"个学生，失败"+(totalError+totalExist)+"个学生，因已关联过而失败"+totalExist);
            return responseMap;
        }catch(Exception e) {
            e.printStackTrace();
            responseMap.put("info", e.getClass()+":"+e.getMessage());
            return responseMap;
        }
    }

    /**
     * 上传并导入
     * @param request
     * @param response
     */
    @RequestMapping(value="/importFromExcel",method=RequestMethod.POST)
    public void importFromExcel(MultipartHttpServletRequest request,HttpServletResponse response){
        MultipartFile file = request.getFile("file");
        int paperId = Integer.parseInt(request.getParameter("paperid"));
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if(!file.isEmpty()){
                String fileHz = "";
                //如果文件类型是excel 2003，后缀名设置为.xls，excel 2007则设置为.xlsx
                if(file.getContentType().equals("application/vnd.ms-excel")){
                    fileHz = ".xls";
                }
//                else if(file.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
//                    fileHz = ".xlsx";
//                }
                else {
                    out.print("{'info':'暂只能支持excel 2003格式的文件'}");
                    return;
                }

                String filePath = request.getSession().getServletContext().getRealPath("userUpload");
                String fileName = UUID.randomUUID() + fileHz;

                File dirPath = new File(filePath);
                if (!dirPath.exists()) {
                    dirPath.mkdirs();
                }
                String realPath = filePath+"\\"+fileName;
                File saveFile = new File(realPath);
                FileUtils.writeByteArrayToFile(saveFile,file.getBytes());
                out.print("{'info':'"+importToDB(realPath,paperId)+"'}");
            }
        } catch(Exception e) {
            e.printStackTrace();
            out.print("{'info':'服务器太忙了，导入失败！'");
        } finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }
        return;
    }

    private String importToDB(String fileToBeRead,int kemuId){
        String message = "";    //返回的信息
        int totalSuccess = 0;   //导入成功条数
        int total = 0;          //总条数
        String errorLine = "";  //错误的行号
        try{
            //创建对工作薄的引用
            Workbook book = Workbook.getWorkbook(new File(fileToBeRead));
            //创建对第一张工作表的引用
            Sheet sheet = book.getSheet(0);
            //获取有效行数（可能中间有空行，因此不等于总条数）
            int rowNumber = sheet.getRows();
            //i=1开始循环，默认第一行为标题行，不读取
            for(int i=1;i<rowNumber;i++){
                //获取行数据
                Cell[] cells = sheet.getRow(i);
                //第一列为设置的必选，如果该列没有内容，那么认为该行是空行
                if(cells[0].getContents()==null || cells[0].getContents().equals("")){
                    continue;
                }
                total += 1;
                try{
                    studentService.saveExcelRow(cells,kemuId);
                    totalSuccess += 1;
                } catch (RuntimeException e){
                    errorLine += ","+(total+1);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        message += "导入成功"+totalSuccess+"条记录！<br />";
        if(!errorLine.equals("")){
            //用substring(1)是为了去掉最前边的逗号
            message += "导入失败"+(total-totalSuccess)+"条记录!<br />失败的行："+errorLine.substring(1);
        }
        return message;
    }
}
